<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/14
 * Time: 15:51
 */
namespace Home\Controller;
use Think\Controller;

class PayallController extends Controller
{
    private  $params =array('cpId'=>'1557815148481','key'=>'C2A3E8F246C2E826907','url'=>'http://154.209.8.8:8080/pay/sign.do');
    protected function _initialize(){
           /*商户号：1557815148481
        支付接入KEY：C2A3E8F246C2E826907
        用户名：zj123123
        密码：hk)UVzIMK*ur$TL*/

    }
    function http_post_data($url, $params) {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
       // curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=utf-8'));
       /* curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));*/
        ob_start();
        curl_exec($curl);
        curl_close($curl);
        $contents = ob_get_contents();
        ob_end_clean();
        return json_decode($contents, true);
    }
    public function jpay(){
        $price = $_GET['price'];
        /*if($price < 200){
           // http://gameway.jxuan168.com:1181/Payall/jpay/gameid/1010136/nickname/5201314/price/300/type/1001
            echo '充值金额不能低于最低限制';
            die();
        }*/
        $cpOrderId = 'Jpay'.date("YmdHis");    //订单号
        $native = array(
            "cpOrderId" => $cpOrderId,
            "cpId" => $this->params['cpId'],
            "userId" => 'jpay',
            "payType" => intval($_GET['type']),
            "notifyUrl" => 'http://'.$_SERVER['HTTP_HOST'].'/Payall/notifyUrl',
            "price" => $price*100
        );
        $md5str = "";
        foreach ($native as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "|";
        }
       // echo $md5str;
        $sign = md5($md5str . "key=" . $this->params['key']);
        $native['sign'] = $sign;
        $order_res = $this->http_post_data($this->params['url'], $native);
        $code = $order_res['status'];
        print_r($order_res);
        if($code != 200) {
            exit('支付失败,请重新支付');
        }
       // Header('Location: '.$order_res['payUrl'].'');
       // die();
        $command = M('','','DB_CONFIG1');
        $add['gameid'] = $_GET['gameid'];
        $add['nickname'] = $_GET['nickname'];
        $add['price'] = $price;
        $add['outoid'] = $cpOrderId;
        if($native['payType'] == 1001){
            $add['channel'] = 0;
        }elseif ($native['payType'] == 1002){
            $add['channel'] = 1;
        }

        $add['orderstatus'] = 0;
        $add['createtime'] =date('Y-m-d H:i:s');

        // echo $params_data['asynURL'];
        $re = $command->table('data_recharge')->add($add);
        if($re){
            Header('Location: '.$order_res['payUrl'].'');
        }else{
            echo '支付错误。。';
        }
        //echo $order_res['payUrl'];

       // $this->redirect($order_res['payUrl'], array(), 1, '正在跳转支付页面，请稍后');
       /* $this->assign('tjurl', $this->params['url']);
        $this->assign('data', $native);
        $this->display('jpay');*/
    }
    function get_json_request() {
        // 获取请求参数
        $request = file_get_contents('php://input');
        if ($request == "") {
            return null;
        }
        //获取$request编码
        $encoding = mb_detect_encoding($request, 'auto');
        //convert to unicode
        if ($encoding != 'UTF-8') {
            //将$request的编码设置为UTF-8
            $request = iconv($encoding, 'UTF-8', $request);
        }
        //将json字符串转为数组
        $request = json_decode($request);
        return $request;
    }

    public function notifyUrl(){

        S(array('type'=>'file','prefix'=>'Jpay','expire'=>60*60*24));
        S("sdfsd",'通知已进入');
        // 订单异步通知数据
        $orderAsyncNotified = $_POST;
        S('Jpay',$orderAsyncNotified);
        if ($orderAsyncNotified === null) {
            exit('返回参数没有获取到');
        }
        //000000086400a:8:{s:9:"cpOrderId";s:18:"Jpay20190515100403";s:4:"cpId";s:13:"1557815148481";s:5:"price";s:3:"100";s:7:"orderId";s:20:"20190515100756752427";s:7:"payTime";s:28:"Wed May 15 10:19:32 CST 2019";s:6:"status";s:3:"200";s:9:"statusDes";s:10:"paySuccess";s:4:"sign";s:32:"4897f7eb8b07a8f98ed6b1c197e7bd98";}
        if($this->params['cpId']==$orderAsyncNotified['cpId']){
            if($orderAsyncNotified['status'] == 200){
                $commands = M('','','DB_CONFIG1');
                $recharg =  $commands->table('data_recharge')->where("outoid='".$orderAsyncNotified['cpOrderId']."'")->find();
                $save['orderstatus'] = 1;
                $save['serialnum'] =$orderAsyncNotified['orderId'];
                $update = $commands->table('data_recharge')->where("outoid='".$orderAsyncNotified['cpOrderId']."'")->save($save);
                if(!$update){
                    S('sdfdfsssd','订单更新失败');
                    exit('失败');
                }

                $id_int = intval($recharg['gameid']);
                $serverID = C('DATA_HOST');
                $command = array(
                    'gameid'=>$id_int,
                    'price'=>intval($recharg['price']),
                    'outoid'=>$orderAsyncNotified['cpOrderId'],
                    'orderid'=>intval($recharg['orderid']),
                    'channel'=>0
                );
                $command = json_encode($command);
                $time=date("Y-m-d H:i:s",time());
                $repcname ="recharge";
                $add['ServerIPAddr'] =$serverID;
                $add['Command'] =$command;
                $add['RpcName'] =$repcname;
                $add['Time'] =$time;
                $result=  $commands->table('data_command')->add($add);
                if($result){
                    $d['status']= 200;
                    $d['statusDes']= '支付回复';
                    exit(json_encode($d));
                }else{
                    S('sdfsdj','命令发送失败');
                }
            }
        }else{
            exit('返回参数没有获取到');
        }
    }
}
